package com.atguigu.gulimall.product.service.impl;

import com.atguigu.common.utils.PageUtils;
import com.atguigu.common.utils.Query;
import com.atguigu.gulimall.product.dao.CategoryDao;
import com.atguigu.gulimall.product.entity.CategoryEntity;
import com.atguigu.gulimall.product.service.CategoryBrandRelationService;
import com.atguigu.gulimall.product.service.CategoryService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;


@Service("categoryService")
public class CategoryServiceImpl extends ServiceImpl<CategoryDao, CategoryEntity> implements CategoryService {

//    @Autowired
//    CategoryDao categoryDao;
    @Autowired
    private CategoryBrandRelationService categoryBrandRelationService;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<CategoryEntity> page = this.page(
                new Query<CategoryEntity>().getPage(params),
                new QueryWrapper<CategoryEntity>()
        );

        return new PageUtils(page);
    }

    @Override
    public List<CategoryEntity> listWithTree() {
        // 1.查出所有分类
        List<CategoryEntity> entities = baseMapper.selectList(null);
        // 2.组装成父子树型结构
        // 2.1 找到所有的一级分类
//        List<CategoryEntity> leve1Menus = entities.stream().filter((CategoryEntity)->{
//            return CategoryEntity.getParentCid() == 0;
//        }).collect(Collectors.toList());
        // 简化写法
        List<CategoryEntity> leve1Menus = entities.stream().filter(CategoryEntity->
            CategoryEntity.getParentCid() == 0
        ).map((menu)->{
            menu.setChildren(getChildens(menu,entities));
            return menu;
        }).sorted((menu1,menu2)->{
            return (menu1.getSort()==null?0:menu1.getSort()) - (menu2.getSort()==null?0:menu2.getSort());
        }).collect(Collectors.toList());
        return leve1Menus;
    }

    @Override
    public void removeMenuByIds(List<Long> asList) {
        //TODO 1、检查当前删除的菜单，是否被别的地方引用
        baseMapper.deleteBatchIds(asList);
    }

    /**
     * 获取catelogId的完整路径
     * @param catelogId
     * @return
     */
    @Override
    public Long[] findCategoryPath(Long catelogId) {
        // [2,25,225]
        List<Long> paths = new ArrayList<>();
        List<Long> partentPath = findPartentPath(catelogId, paths);
        // 使用集合工具类逆序转换partentPath（225,25,2 -> 2,25,225）
        Collections.reverse(partentPath);
        return partentPath.toArray(new Long[partentPath.size()]);
    }

    /**
     * 级联更新所欲的关联数据
     * @param category
     */
    @Override
    public void updateCascade(CategoryEntity category) {
        // 保证冗余字段的数据一致
        // 先把自己表里的分类更新
        this.updateById(category);
        // 若此次更新有更新分类名字
        if(StringUtils.isNotEmpty(category.getName())){
            // 同步更新其他关联表中的数据，注入CategoryBrandRelationService
            categoryBrandRelationService.updateCategory(category.getCatId(),category.getName());
            //TODO 更新其他关联
        }
    }

    // 225,25,2
    private List<Long> findPartentPath(Long catelogId, List<Long> paths) {
        // 收集当前节点id
        paths.add(catelogId);
        CategoryEntity byId = this.getById(catelogId);
        if (byId.getParentCid() != 0){ //如果当前id存在父id
            findPartentPath(byId.getParentCid(), paths);
        }
        return paths;
    }

    //遍历查找所有菜单的子菜单
    private List<CategoryEntity> getChildens(CategoryEntity root,List<CategoryEntity> all){
        List<CategoryEntity> childen = all.stream().filter((CategoryEntity)->{
            return CategoryEntity.getParentCid().equals(root.getCatId());
        }).map((CategoryEntity)->{
            // 1.找到子菜单
            CategoryEntity.setChildren(getChildens(CategoryEntity,all));
            return CategoryEntity;
        }).sorted((menu1,menu2)->{
            // 2.菜单的排序
            return (menu1.getSort()==null?0:menu1.getSort()) - (menu2.getSort()==null?0:menu2.getSort());
        }).collect(Collectors.toList());
        return childen;
    }

}